package com.module.TraceSource.dao;

import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;

import com.module.TraceSource.vo.TsDefEventItem;
import com.module.TraceSource.vo.TsEntEvent;
import com.module.TraceSource.vo.TsEntEventItem;

import base.dao.GenericHibernateDao;
import base.util.Page;


public class TsEntEventItemDao extends GenericHibernateDao<TsEntEventItem, Long>{
	private static TsEntEventItemDao dao;

	public TsEntEventItemDao() {
		super();
	}
	
	public synchronized static TsEntEventItemDao getInstance(){
		if(dao == null){
			dao = new TsEntEventItemDao();
		}
		return dao;
	}
	
	/**
	 * 获取溯源流程取得溯源流程操作项
	 * @param entFlowIds
	 * @return
	 */
	public List<TsEntEventItem> getTsEntEventItem(Session session,Map<String,Object> map) {
		String hql = "";
		String entEventId = "";
		
		if(map!=null){
			entEventId = (String) map.get("eventId");
		}
		
		//按照顺序号排序
		hql = "from TsEntEventItem as obj where obj.status !='D' and obj.eventid = '" + entEventId + "' ";
		
		Query query = session.createQuery(hql.toString());
		
		List<TsEntEventItem> tsEntEventItem = query.list();
		
		return tsEntEventItem;
		}
	
	/**
	 * 分页列出操作事项字段列表
	 * @param session
	 * @param obj
	 * @param page
	 * @return
	 */
	public Page getList(Session session, TsEntEventItem obj, Page page) {
		String hql1 = "from TsEntEventItem as obj where obj.status !='D' ";
		String hql2 = "select count(*) from TsEntEventItem as obj where obj.status !='D' ";
		if(obj.getEventid()!=null && obj.getEventid()!=0){
			hql1=hql1 +  " and obj.eventid = "+obj.getEventid();
            hql2=hql2 +  " and obj.eventid = "+obj.getEventid();
		}
		Query query = session.createQuery(hql1);
        query.setFirstResult(page.getStart()).setMaxResults(page.getLimit());
        page.setTotal((long) ((Long) session.createQuery(hql2)
                .uniqueResult()).intValue());
        page.setRows(query.list());
		return page;
	}

	/**
	 * 从eventItemList中复制生成TsEntEventItem，并保存
	 * @param session
	 * @param entEvent
	 * @param eventItemList
	 */
	public void saveEventItemList(Session session, TsEntEvent entEvent,
			List<TsDefEventItem> eventItemList) {
		for(TsDefEventItem defEventItem : eventItemList){
			TsEntEventItem entEventItem = TsEntEventItem.copyEntEventItem(defEventItem);
			entEventItem.setEventid(entEvent.getId());
			save(session, entEventItem);
		}
	}
}
